package com.yyx.app1.Data.Medication;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.yyx.app1.Data.DataInit;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by yuexing on 2015/9/25.
 */
public class Medication_SQLiteOperation {
    private DataInit dataInit;
    private String TableName;

    public Medication_SQLiteOperation(DataInit dataInit) {
        this.dataInit = dataInit;
        TableName = dataInit.getDB_MedicationTableName();
    }

    public void add_safe(Medicine medicine)//已经有了就不添加
    {
        if (!find(medicine.getMedicineName()))
        {
            add(medicine);
        }
    }

    public void deleteAll()
    {
        SQLiteDatabase db=null;
        try
        {
            db = dataInit.creatOrOpenDatabase();
            db.execSQL("delete from " + TableName + " ;");
//            db.execSQL("update "+TableName+" SET number = 0 ;");
        }
        catch (Exception e)
        {
           Log.e("异常1509301856",e.toString());
        }
        finally
        {
            Log.i("medication", "deleteAll");
            if (db!=null)
                db.close();
        }
    }

    public long add(Medicine medicine) {
        long result=0;
        SQLiteDatabase db=null;
        try
        {
            db = dataInit.creatOrOpenDatabase();
            ContentValues values = new ContentValues();
            values.put("id",medicine.getId());//private String id;
            values.put("medicineName",medicine.getMedicineName());//private String medicineName;     //药品名字
            values.put("adminId",medicine.getAdminId());//private Integer adminId;         //管理员id
            values.put("medicineFactory",medicine.getMedicineFactory());//private String medicineFactory;  //生产厂家
            values.put("address",medicine.getAddress());//private String address;          //厂家地址
            values.put("belongToColumn",medicine.getBelongToColumn());//private Integer belongToColumn;  //所属栏目
            values.put("explain",medicine.getExplain());//private String explain;          //补充说明
            values.put("medicineImage",medicine.getMedicineImage());//private String medicineImage;    //药品图片
            values.put("addtime",medicine.getAddtime());//private String addtime;          //时间
            values.put("pinyin",medicine.getPinyin());//private String pinyin;           //汉语拼音
            values.put("englishName",medicine.getEnglishName());//private String englishName;      //英文名称
            values.put("petName",medicine.getPetName());//private String petName;          //别名
            values.put("medicineContent",medicine.getMedicineContent());//private String medicineContent;  //主要成分
            values.put("shape",medicine.getShape());//private String shape;            //性状
            values.put("preparation",medicine.getPreparation());//private String preparation;      //制剂与规格
            values.put("functionDosage",medicine.getFunctionDosage());//private String functionDosage;   //用法用量
            values.put("cureFun",medicine.getCureFun());//private String cureFun;          //药理作用
            values.put("drugInteraction",medicine.getDrugInteraction());//private String drugInteraction;  //药物相互作用
            values.put("indication",medicine.getIndication());//private String indication;       //适应症
            values.put("clinical",medicine.getClinical());//private String clinical;         //临床应用
            values.put("effect",medicine.getEffect());//private String effect;           //不良反应
            values.put("attention",medicine.getAttention());//private String attention;        //注意事项
            values.put("contraindication",medicine.getContraindication());//private String contraindication; //禁忌症
            values.put("status",medicine.getStatus());//private Integer status;           //状态   0：创建  1：上架   -1：下架
            values.put("onTime",medicine.getOnTime());//private String onTime;            //上架时间
            values.put("offTime",medicine.getOffTime());//private String offTime;           //下架时间
            values.put("firstId",medicine.getFirstId());//private String firstId;            //关联一级栏目
            values.put("columnName",medicine.getColumnName());//private String columnName;       //所属栏目名称
            values.put("firstUrl",medicine.getFirstUrl());//private String firstUrl;       //一级栏目url
            values.put("secondUrl",medicine.getSecondUrl());//private String secondUrl;       //二级栏目url
            result = db.insert(TableName,null,values);
        }
        catch (Exception e)
        {
           Log.e("异常1510141111",e.toString());
        }
        finally
        {
            if (db!=null)
                db.close();
            return result;
        }
    }

    public long add(Medicine medicine,SQLiteDatabase db) {
        long result=0;
        try
        {
            ContentValues values = new ContentValues();
            values.put("id",medicine.getId());//private String id;
            values.put("medicineName",medicine.getMedicineName());//private String medicineName;     //药品名字
            values.put("adminId",medicine.getAdminId());//private Integer adminId;         //管理员id
            values.put("medicineFactory",medicine.getMedicineFactory());//private String medicineFactory;  //生产厂家
            values.put("address",medicine.getAddress());//private String address;          //厂家地址
            values.put("belongToColumn",medicine.getBelongToColumn());//private Integer belongToColumn;  //所属栏目
            values.put("explain",medicine.getExplain());//private String explain;          //补充说明
            values.put("medicineImage",medicine.getMedicineImage());//private String medicineImage;    //药品图片
            values.put("addtime",medicine.getAddtime());//private String addtime;          //时间
            values.put("pinyin",medicine.getPinyin());//private String pinyin;           //汉语拼音
            values.put("englishName",medicine.getEnglishName());//private String englishName;      //英文名称
            values.put("petName",medicine.getPetName());//private String petName;          //别名
            values.put("medicineContent",medicine.getMedicineContent());//private String medicineContent;  //主要成分
            values.put("shape",medicine.getShape());//private String shape;            //性状
            values.put("preparation",medicine.getPreparation());//private String preparation;      //制剂与规格
            values.put("functionDosage",medicine.getFunctionDosage());//private String functionDosage;   //用法用量
            values.put("cureFun",medicine.getCureFun());//private String cureFun;          //药理作用
            values.put("drugInteraction",medicine.getDrugInteraction());//private String drugInteraction;  //药物相互作用
            values.put("indication",medicine.getIndication());//private String indication;       //适应症
            values.put("clinical",medicine.getClinical());//private String clinical;         //临床应用
            values.put("effect",medicine.getEffect());//private String effect;           //不良反应
            values.put("attention",medicine.getAttention());//private String attention;        //注意事项
            values.put("contraindication",medicine.getContraindication());//private String contraindication; //禁忌症
            values.put("status",medicine.getStatus());//private Integer status;           //状态   0：创建  1：上架   -1：下架
            values.put("onTime",medicine.getOnTime());//private String onTime;            //上架时间
            values.put("offTime",medicine.getOffTime());//private String offTime;           //下架时间
            values.put("firstId",medicine.getFirstId());//private String firstId;            //关联一级栏目
            values.put("columnName",medicine.getColumnName());//private String columnName;       //所属栏目名称
            values.put("firstUrl",medicine.getFirstUrl());//private String firstUrl;       //一级栏目url
            values.put("secondUrl",medicine.getSecondUrl());//private String secondUrl;       //二级栏目url
            result = db.insert(TableName,null,values);
        }
        catch (Exception e)
        {
           Log.e("异常1510141112",e.toString());
        }
        finally
        {
            return result;
        }
    }

    public List<HashMap<String,String>> fuzzySearch(String searchname)
    {
        List<HashMap<String,String>> list=new ArrayList<>();
        SQLiteDatabase db=null;
        Cursor cursor=null;
        try
        {
            db = dataInit.creatOrOpenDatabase();
            cursor = db.query(TableName,new String[]{"medicineName,englishName,indication"},"medicineName like ?",new String[]{"%"+searchname+"%"},null,null,null,null);
            while (cursor.moveToNext())
            {
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("medicineName",cursor.getString(cursor.getColumnIndex("medicineName")));
                hashMap.put("englishName", cursor.getString(cursor.getColumnIndex("englishName")));
                hashMap.put("indication", cursor.getString(cursor.getColumnIndex("indication")));
                list.add(hashMap);
            }
        }
        catch (Exception e)
        {
           Log.e("异常1510141113",e.toString());
        }
        finally
        {
            if (cursor!=null)
                cursor.close();
            if (db!=null)
                db.close();
            return list;
        }
    }

    public boolean find(String medicineName) {
        boolean result=false;
        SQLiteDatabase db=null;
        try
        {
            db = dataInit.creatOrOpenDatabase();
            Cursor cursor = db.query(TableName, null, "medicineName=?", new String[]{medicineName}, null, null, null);
            result = cursor.moveToNext();
            cursor.close();
        }
        catch (Exception e)
        {
           Log.e("异常1510141114",e.toString());
        }
        finally
        {
            if (db!=null)
                db.close();
            return result;
        }
    }

    public int delete(String medicineName) {
        int count=0;
        SQLiteDatabase db=null;
        try
        {
            db = dataInit.creatOrOpenDatabase();
            count = db.delete(TableName, "medicineName=?", new String[]{medicineName});
        }
        catch (Exception e)
        {
           Log.e("异常",e.toString());
        }
        finally
        {
            if (db!=null)
                db.close();
            return count;
        }
    }

    public JSONObject getByMedicineName(String medicineName) {
        SQLiteDatabase db=null;
        Cursor cursor=null;
        JSONObject jsonObject=new JSONObject();
        try
        {
            db = dataInit.creatOrOpenDatabase();
            cursor = db.query(TableName, null, "medicineName=?", new String[]{medicineName}, null, null, null, null);
            if (cursor.moveToNext())
            {
                jsonObject.put("id",cursor.getString(cursor.getColumnIndex("id")));    //private String id;
                jsonObject.put("medicineName",cursor.getString(cursor.getColumnIndex("medicineName")));    //private String medicineName;     //药品名字
                jsonObject.put("adminId",cursor.getInt(cursor.getColumnIndex("adminId")));    //private Integer adminId;         //管理员id
                jsonObject.put("medicineFactory",cursor.getString(cursor.getColumnIndex("medicineFactory")));    //private String medicineFactory;  //生产厂家
                jsonObject.put("address",cursor.getString(cursor.getColumnIndex("address")));    //private String address;          //厂家地址
                jsonObject.put("belongToColumn",cursor.getInt(cursor.getColumnIndex("belongToColumn")));    //private Integer belongToColumn;  //所属栏目
                jsonObject.put("explain",cursor.getString(cursor.getColumnIndex("explain")));    //private String explain;          //补充说明
                jsonObject.put("medicineImage",cursor.getString(cursor.getColumnIndex("medicineImage")));    //private String medicineImage;    //药品图片
                jsonObject.put("addtime",cursor.getString(cursor.getColumnIndex("addtime")));    //private String addtime;          //时间
                jsonObject.put("pinyin",cursor.getString(cursor.getColumnIndex("pinyin")));    //private String pinyin;           //汉语拼音
                jsonObject.put("englishName",cursor.getString(cursor.getColumnIndex("englishName")));    //private String englishName;      //英文名称
                jsonObject.put("petName",cursor.getString(cursor.getColumnIndex("petName")));    //private String petName;          //别名
                jsonObject.put("medicineContent",cursor.getString(cursor.getColumnIndex("medicineContent")));    //private String medicineContent;  //主要成分
                jsonObject.put("shape",cursor.getString(cursor.getColumnIndex("shape")));    //private String shape;            //性状
                jsonObject.put("preparation",cursor.getString(cursor.getColumnIndex("preparation")));    //private String preparation;      //制剂与规格
                jsonObject.put("functionDosage",cursor.getString(cursor.getColumnIndex("functionDosage")));    //private String functionDosage;   //用法用量
                jsonObject.put("cureFun",cursor.getString(cursor.getColumnIndex("cureFun")));    //private String cureFun;          //药理作用
                jsonObject.put("drugInteraction",cursor.getString(cursor.getColumnIndex("drugInteraction")));    //private String drugInteraction;  //药物相互作用
                jsonObject.put("indication",cursor.getString(cursor.getColumnIndex("indication")));    //private String indication;       //适应症
                jsonObject.put("clinical",cursor.getString(cursor.getColumnIndex("clinical")));    //private String clinical;         //临床应用
                jsonObject.put("effect",cursor.getString(cursor.getColumnIndex("effect")));    //private String effect;           //不良反应
                jsonObject.put("attention",cursor.getString(cursor.getColumnIndex("attention")));    //private String attention;        //注意事项
                jsonObject.put("contraindication",cursor.getString(cursor.getColumnIndex("contraindication")));    //private String contraindication; //禁忌症
                jsonObject.put("status",cursor.getInt(cursor.getColumnIndex("status")));    //private Integer status;           //状态   0：创建  1：上架   -1：下架
                jsonObject.put("onTime",cursor.getString(cursor.getColumnIndex("onTime")));    //private String onTime;            //上架时间
                jsonObject.put("offTime",cursor.getString(cursor.getColumnIndex("offTime")));    //private String offTime;           //下架时间
                jsonObject.put("firstId",cursor.getString(cursor.getColumnIndex("firstId")));    //private String firstId;            //关联一级栏目
                jsonObject.put("columnName",cursor.getString(cursor.getColumnIndex("columnName")));    //private String columnName;       //所属栏目名称
                jsonObject.put("firstUrl",cursor.getString(cursor.getColumnIndex("firstUrl")));    //private String firstUrl;       //一级栏目url
                jsonObject.put("secondUrl",cursor.getString(cursor.getColumnIndex("secondUrl")));    //private String secondUrl;       //二级栏目url
            }
        }
        catch (Exception e)
        {
           Log.e("异常",e.toString());
        }
        finally
        {
            if (cursor!=null)
                cursor.close();
            if (db!=null)
                db.close();
            return jsonObject;
        }
    }

    public List getDemo_10name() {
        SQLiteDatabase db=null;
        Cursor cursor=null;
        List<String> list=new ArrayList<>();
        try
        {
            db = dataInit.creatOrOpenDatabase();
            cursor = db.query(TableName, new String[]{"medicineName"}, null, null,null,null,null);
            int i=0;
            while (cursor.moveToNext())
            {
                if (i>14)
                {
                    break;
                }
                list.add(cursor.getString(cursor.getColumnIndex("medicineName")));
                ++i;
            }
        }
        catch (Exception e)
        {
           Log.e("异常",e.toString());
        }
        finally
        {
            if (cursor!=null)
                cursor.close();
            if (db!=null)
                db.close();
            return list;
        }
    }

    public List getDemo_10nameInfo() {
        SQLiteDatabase db=null;
        Cursor cursor=null;
        List<HashMap<String,String>> list=new ArrayList<>();
        try
        {
            db = dataInit.creatOrOpenDatabase();
            cursor = db.query(TableName, new String[]{"medicineName,englishName,indication"}, null, null,null,null,null);
            int i=0;
            while (cursor.moveToNext())
            {
                if (i>10)
                {
                    break;
                }
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("medicineName",cursor.getString(cursor.getColumnIndex("medicineName")));
                hashMap.put("englishName", cursor.getString(cursor.getColumnIndex("englishName")));
                hashMap.put("indication", cursor.getString(cursor.getColumnIndex("indication")));
                list.add(hashMap);
                ++i;
            }
        }
        catch (Exception e)
        {
           Log.e("异常",e.toString());
        }
        finally
        {
            if (cursor!=null)
                cursor.close();
            if (db!=null)
                db.close();
            return list;
        }
    }

    public List getMedicationBySecond(String id) {
        SQLiteDatabase db=null;
        Cursor cursor=null;
        List<String> list=new ArrayList<>();
        try
        {
            db = dataInit.creatOrOpenDatabase();
            cursor = db.query(TableName, new String[]{"medicineName"}, "belongToColumn=?", new String[]{id},null,null,null);
            while (cursor.moveToNext())
            {
                list.add(cursor.getString(cursor.getColumnIndex("medicineName")));
            }
        }
        catch (Exception e)
        {
           Log.e("异常",e.toString());
        }
        finally
        {
            if (cursor!=null)
                cursor.close();
            if (db!=null)
                db.close();
            return list;
        }
    }

    public void InjectionSQList()
    {
        SQLiteDatabase db = dataInit.creatOrOpenDatabase();
        File file=new File(dataInit.getDataBaseDirectory()+"/"+dataInit.getMedicationDataFileName());
        try
        {
            BufferedReader bufferedReader=new BufferedReader(new FileReader(file));
            String strline = null;
            while ((strline=bufferedReader.readLine())!=null)
            {
                JSONObject jsonObject=new JSONObject(strline);
                Medicine medicine = new Medicine();
                medicine.setId(jsonObject.getString("id"));//private String id;
                medicine.setMedicineName(jsonObject.getString("medicineName"));//private String medicineName;     //药品名字
                medicine.setAdminId(jsonObject.getInt("adminId"));//private Integer adminId;         //管理员id
                medicine.setMedicineFactory(jsonObject.getString("medicineFactory"));//private String medicineFactory;  //生产厂家
                medicine.setAddress(jsonObject.getString("address"));//private String address;          //厂家地址
                medicine.setBelongToColumn(jsonObject.getInt("belongToColumn"));//private Integer belongToColumn;  //所属栏目
                medicine.setExplain(jsonObject.getString("explain"));//private String explain;          //补充说明
                medicine.setMedicineImage(jsonObject.getString("medicineImage"));//private String medicineImage;    //药品图片
                medicine.setAddtime(jsonObject.getString("addtime"));//private String addtime;          //时间
                medicine.setPinyin(jsonObject.getString("pinyin"));//private String pinyin;           //汉语拼音
                medicine.setEnglishName(jsonObject.getString("englishName"));//private String englishName;      //英文名称
                medicine.setPetName(jsonObject.getString("petName"));//private String petName;          //别名
                medicine.setMedicineContent(jsonObject.getString("medicineContent"));//private String medicineContent;  //主要成分
                medicine.setShape(jsonObject.getString("shape"));//private String shape;            //性状
                medicine.setPreparation(jsonObject.getString("preparation"));//private String preparation;      //制剂与规格
                medicine.setFunctionDosage(jsonObject.getString("functionDosage"));//private String functionDosage;   //用法用量
                medicine.setCureFun(jsonObject.getString("cureFun"));//private String cureFun;          //药理作用
                medicine.setDrugInteraction(jsonObject.getString("drugInteraction"));//private String drugInteraction;  //药物相互作用
                medicine.setIndication(jsonObject.getString("indication"));//private String indication;       //适应症
                medicine.setClinical(jsonObject.getString("clinical"));//private String clinical;         //临床应用
                medicine.setEffect(jsonObject.getString("effect"));//private String effect;           //不良反应
                medicine.setAttention(jsonObject.getString("attention"));//private String attention;        //注意事项
                medicine.setContraindication(jsonObject.getString("contraindication"));//private String contraindication; //禁忌症
                medicine.setStatus(jsonObject.getInt("status"));//private Integer status;           //状态   0：创建  1：上架   -1：下架
                medicine.setOnTime(jsonObject.getString("onTime"));//private String onTime;            //上架时间
                medicine.setOffTime(jsonObject.getString("offTime"));//private String offTime;           //下架时间
                medicine.setFirstId(jsonObject.getString("firstId"));//private String firstId;            //关联一级栏目
                medicine.setColumnName(jsonObject.getString("columnName"));//private String columnName;       //所属栏目名称
                medicine.setFirstUrl(jsonObject.getString("firstUrl"));//private String firstUrl;       //一级栏目url
                medicine.setSecondUrl(jsonObject.getString("secondUrl"));//private String secondUrl;       //二级栏目url
                add(medicine,db);
            }
            bufferedReader.close();
        }
        catch (Exception e)
        {
           Log.e("异常", e.toString());
        }
        finally
        {
            Log.i("medication", "结束");
            if (db!=null)
                db.close();
        }
    }
}
